package org.xkx.demo.netty.hello.server;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.charset.Charset;
import java.time.LocalDateTime;

public class HelloServerHandler extends ChannelInboundHandlerAdapter {
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		ByteBuf buf = (ByteBuf) msg;
		byte[] bytes = new byte[buf.readableBytes()];
		buf.readBytes(bytes);
		String str = new String(bytes, Charset.forName("UTF-8"));
		System.out.println("接收的消息：" + str);
		String resp = null;
		if(null != str && "你好服务端！".equals(str)){
			LocalDateTime dt = LocalDateTime.now();
			resp = "你好客户端：" + dt;
		}else{
			resp = "非法访问";
		}
		System.out.println("发送的消息：" + resp);
		ByteBuf respBuf = Unpooled.copiedBuffer(resp.getBytes("UTF-8"));
		ctx.write(respBuf);
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		ctx.flush();
		super.channelReadComplete(ctx);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		ctx.close();
		super.exceptionCaught(ctx, cause);
	}
}
